package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 处理文件上传下载
 */
@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     *要求1.上传到目录需要配置
     *要求2.长传的文件名不能重复
     * 要求3.需要将生成的文件名相应给客户端
     */

    @PostMapping("upload")
    public R<String> upload(MultipartFile file)throws IOException {
        //1.判断目录是否存在
        File dir = new File(basePath);
        if(!dir.exists()){
            //创建目录
            dir.mkdirs();
        }
        //2.生成一个唯一的文件名
        String uuid = UUID.randomUUID().toString();

        //获取原始文件名的后缀jpg,gif,png
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String uuidFileName = uuid + suffix;

        //3.将临时文件存入指定路径
        file.transferTo(new File(basePath+"/"+uuidFileName));


        return R.success(uuidFileName);

    }

    /**
     * 文件下下载
     * @return
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse resp)throws IOException {
        //文件下载：将文件以流的形式写给客户端
        //输入流：文件的流            输出流：response.getOutputStream
        FileInputStream is = new FileInputStream(basePath + "/"+name);
        ServletOutputStream os = resp.getOutputStream();
        IOUtils.copy(is,os);
        is.close();
    }

}
